package tn.vermeg.jee.tweetVermeg.business;

import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.validation.ValidationException;

import org.apache.ws.scout.model.uddi.v2.Contact;

import tn.vermeg.jee.tweetVermeg.model.Tweet;


/**
 *
 * @author yosra
 */
@Stateless

public class MainModule {
    private EntityManager em;

    
    protected EntityManager getEntityManager() {
        return em;
    }
    
     public void tweet(Tweet t) {
        em.persist(t);

    }
     public void inscrire(Contact c){
         em.persist(c);
     }
      public Contact authenticate(String email, String pwd) {
        Contact contact;
        Query q0;
        if (email == null || "".equals(email)) {
            throw new ValidationException("Le nom du client est non valide");
        }
        String q = "SELECT c FROM Contact c WHERE c.email=:email";
        q0=em.createQuery(q);
        q0.setParameter("email", email);
        contact = (Contact) q0.getSingleResult();
        if (contact != null) {
            contact.matchPassword(pwd);
        }
        return contact;


    }
    
    public void retweet(Tweet t, Long idAncestor){
        t.setTweetAcestor(em.find(Tweet.class, idAncestor));
        em.persist(t);
        
    }
    
    public List<Tweet> getTweets(Long contactId){
        List<Tweet> all = new ArrayList<Tweet>();
        Contact c = em.find(Contact.class, contactId);
        
        
        String q = "Select object(t) from Tweet t"
                +"where t.contact.Id =:c.Id"
                +"or"
                +"t member of :c.friends"
                +"order by t.date";
        
        
        Query qo = em.createQuery(q);
        qo.setParameter("C",c);
        qo.setMaxResults(50);
        return qo.getResultList();
    
    }
     
    
           
   
}
